File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.148: download - view: text, annotated - select for diffs
Sun Sep 14 15:16:30 2008 UTC (15 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Resource and symb in links to encrypted resources included in CHRT (assessment progress chart) and also STAT (course assessment statistics) need to be encrypted if viewer does not an advanced role (i.e., TA role) to prevent access denied message when following link.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstudentassessment.pm,v 1.148 2008/09/14 15:16:30 raeburn 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 .= '<font color="blue">No Course Data</font>'."\n";
  853: 	} else {
  854: 	    $Str .= '<span class="LC_error">Error getting student data ('.
  855: 		$error.') </span>'."\n";
  856: 	}
  857:         $nodata_count++;
  858:         $r->print($Str);
  859:         $r->rflush();
  860:         return;
  861:     }
  862:     #
  863:     # By sequence build up the data
  864:     my $studentstats;
  865:     my $PerformanceStr = '';
  866:     foreach my $seq (@sequences) {
  867:         my $symb = $seq->symb;
  868:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
  869:         if ($chosen_output->{'tries'}) {
  870:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
  871:                 &student_tries_on_sequence($student,\%StudentsData,
  872:                                            $navmap,$seq,$show_links);
  873:         } else {
  874:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
  875:                 &student_performance_on_sequence($student,\%StudentsData,
  876:                                                  $navmap,$seq,$show_links,
  877:                                                  $chosen_output->{ignore_weight});
  878:         }
  879:         my $ratio='';
  880:         if ($chosen_output->{'every_problem'} && 
  881:             $chosen_output->{'sequence_sum'}) {
  882:             $ratio .= ' ';
  883:         }
  884:         if ($chosen_output->{'sequence_sum'} && $score ne ' ') {
  885:             my $score .= sprintf("%3.0f",$score);
  886:             $ratio .= (' 'x(3-length($score))).$score;
  887:         } elsif($chosen_output->{'sequence_sum'}) {
  888:             $ratio .= ' 'x3;
  889:         }
  890:         if ($chosen_output->{'sequence_max'}) {
  891:             if ($chosen_output->{'sequence_sum'}) {
  892:                 $ratio .= '/';
  893:             }
  894:             $ratio .= sprintf("%3.0f",$seq_max);
  895:         }
  896:         #
  897:         if (! $chosen_output->{'every_problem'}) {
  898:             $performance = '';
  899: 	    $performance_length=0;
  900:         }
  901:         $performance .= ' 'x($width{$symb}->{'width_total'} -
  902:                              $performance_length -
  903:                              $width{$symb}->{'width_sum'}).
  904:             $ratio;
  905:         #
  906:         $Str .= $performance.$padding;
  907:         #
  908:         $studentstats->{$symb}->{'score'}= $score;
  909:         $studentstats->{$symb}->{'max'}  = $seq_max;
  910:     }
  911:     #
  912:     # Total it up and store the statistics info.
  913:     my ($score,$max);
  914:     while (my ($symb,$seq_stats) = each (%{$studentstats})) {
  915:         $Statistics->{$symb}->{'score'} += $seq_stats->{'score'};
  916:         if ($Statistics->{$symb}->{'max'} < $seq_stats->{'max'}) {
  917:             $Statistics->{$symb}->{'max'} = $seq_stats->{'max'};
  918:         }
  919:         if ($seq_stats->{'score'} ne ' ') {
  920:             $score += $seq_stats->{'score'};
  921:             $Statistics->{$symb}->{'num_students'}++;
  922:         }
  923:         $max   += $seq_stats->{'max'};
  924:     }
  925:     if (! defined($score)) {
  926:         $score = ' ' x $total_sum_width;
  927:     } else {
  928:         $score = sprintf("%.0f",$score);
  929:         $score = (' 'x(3-length($score))).$score;
  930:     }
  931:     $Str .= ' '.' 'x($total_sum_width-length($score)).$score.' / '.$max;
  932:     $Str .= " \n";
  933:     #
  934:     $r->print($Str);
  935:     #
  936:     $r->rflush();
  937:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
  938:     return;
  939: }    
  940: 
  941: sub html_finish {
  942:     my ($r) = @_;
  943:     return if (! defined($navmap));
  944:     #
  945:     # Check for suppressed output and close the progress window if so
  946:     $r->print("</pre>\n"); 
  947:     if ($chosen_output->{'summary_table'}) {
  948:         if ($single_student_mode) {
  949:             $r->print(&SingleStudentTotal());
  950:         } else {
  951:             $r->print(&StudentAverageTotal());
  952:         }
  953:     }
  954:     $r->rflush();
  955:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  956:     &html_cleanup();
  957:     return;
  958: }
  959: 
  960: sub StudentAverageTotal {
  961:     my $Str = '<h3>'.&mt('Summary Tables').'</h3>'.$/;
  962:     $Str .= '<table border=2 cellspacing="1">'."\n";
  963:     $Str .= '<tr>'.
  964:         '<th>'.&mt('Title').'</th>'.
  965:         '<th>'.&mt('Average').'</th>'.
  966:         '<th>'.&mt('Maximum').'</th>'.
  967:         '</tr>'.$/;
  968:     foreach my $seq (@sequences) {
  969:         my $symb = $seq->symb;
  970:         my $ave;
  971:         my $num_students = $Statistics->{$symb}->{'num_students'};
  972:         if ($num_students > 0) {
  973:             $ave = int(100*
  974:                        ($Statistics->{$symb}->{'score'}/$num_students)
  975:                        )/100;
  976:         } else {
  977:             $ave = 0;
  978:         }
  979:         my $max = $Statistics->{$symb}->{'max'};
  980:         $ave = sprintf("%.2f",$ave);
  981:         $Str .= '<tr><td>'.$seq->compTitle.'</td>'.
  982:             '<td align="right">'.$ave.'&nbsp;</td>'.
  983:             '<td align="right">'.$max.'&nbsp;'.'</td></tr>'."\n";
  984:     }
  985:     $Str .= "</table>\n";
  986:     return $Str;
  987: }
  988: 
  989: sub SingleStudentTotal {
  990:     return if (! defined($navmap));
  991:     my $student = &Apache::lonstatistics::current_student();
  992:     my $Str = '<h3>'.&mt('Summary table for [_1] ([_2]@[_3])',
  993:                          $student->{'fullname'},
  994:                          $student->{'username'},$student->{'domain'}).'</h3>';
  995:     $Str .= $/;
  996:     $Str .= '<table border=2 cellspacing="1">'."\n";
  997:     $Str .= 
  998:         '<tr>'.
  999:         '<th>'.&mt('Sequence or Folder').'</th>';
 1000:     if ($chosen_output->{'base'} eq 'tries') {
 1001:         $Str .= '<th>'.&mt('Parts Correct').'</th>';
 1002:     } else {
 1003:         $Str .= '<th>'.&mt('Score').'</th>';
 1004:     }
 1005:     $Str .= '<th>'.&mt('Maximum').'</th>'."</tr>\n";
 1006:     my $total = 0;
 1007:     my $total_max = 0;
 1008:     foreach my $seq (@sequences) {
 1009:         my $value = $Statistics->{$seq->symb}->{'score'};
 1010:         my $max = $Statistics->{$seq->symb}->{'max'};
 1011:         $Str .= '<tr><td>'.&HTML::Entities::encode($seq->compTitle).'</td>'.
 1012:             '<td align="right">'.$value.'</td>'.
 1013:                 '<td align="right">'.$max.'</td></tr>'."\n";
 1014:         $total += $value;
 1015:         $total_max +=$max;
 1016:     }
 1017:     $Str .= '<tr><td><b>'.&mt('Total').'</b></td>'.
 1018:         '<td align="right">'.$total.'</td>'.
 1019:         '<td align="right">'.$total_max."</td></tr>\n";
 1020:     $Str .= "</table>\n";
 1021:     return $Str;
 1022: }
 1023: 
 1024: }
 1025: 
 1026: #######################################################
 1027: #######################################################
 1028: 
 1029: =pod
 1030: 
 1031: =head2 EXCEL subroutines
 1032: 
 1033: =item &excel_initialize($r)
 1034: 
 1035: =item &excel_outputstudent($r,$student)
 1036: 
 1037: =item &excel_finish($r)
 1038: 
 1039: =cut
 1040: 
 1041: #######################################################
 1042: #######################################################
 1043: {
 1044: 
 1045: my $excel_sheet;
 1046: my $excel_workbook;
 1047: my $format;
 1048: 
 1049: my $filename;
 1050: my $rows_output;
 1051: my $cols_output;
 1052: 
 1053: my %prog_state; # progress window state
 1054: my $request_aborted;
 1055: 
 1056: my $total_formula;
 1057: my $maximum_formula;
 1058: my %formula_data;
 1059: 
 1060: my $navmap;
 1061: my @sequences;
 1062: 
 1063: sub excel_cleanup {
 1064:     #
 1065:     undef ($excel_sheet);
 1066:     undef ($excel_workbook);
 1067:     undef ($filename);
 1068:     undef ($rows_output);
 1069:     undef ($cols_output);
 1070:     undef (%prog_state);
 1071:     undef ($request_aborted);
 1072:     undef ($total_formula);
 1073:     undef ($maximum_formula);
 1074:     #
 1075:     undef(%formula_data);
 1076:     #
 1077:     undef($navmap);
 1078:     undef(@sequences);
 1079: }
 1080: 
 1081: sub excel_initialize {
 1082:     my ($r) = @_;
 1083: 
 1084:     &excel_cleanup();
 1085:     ($navmap,@sequences) = 
 1086:         &Apache::lonstatistics::selected_sequences_with_assessments();
 1087:     if (! ref($navmap)) {
 1088:         # Unable to get data, so bail out
 1089:         $r->print("<h3>".
 1090:                   &mt('Unable to retrieve course information.').
 1091:                   '</h3>');
 1092:     }
 1093:     #
 1094:     my $total_columns = scalar(&get_student_fields_to_show());
 1095:     my $num_students = scalar(@Apache::lonstatistics::Students);
 1096:     #
 1097:     foreach my $seq (@sequences) {
 1098:         if ($chosen_output->{'every_problem'}) {
 1099:             $total_columns+=&count_parts($navmap,$seq);
 1100:         }
 1101:         # Add 2 because we need a 'sequence_sum' and 'total' column for each
 1102:         $total_columns += 2;
 1103:     }
 1104:     my $too_many_cols_error_message = 
 1105:         '<h2>'.&mt('Unable to Complete Request').'</h2>'.$/.
 1106:         '<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>'.$/.
 1107:         '<p>'.&mt('You may consider reducing the number of <b>Sequences or Folders</b> you have selected.').'</p>'.$/.
 1108:         '<p>'.&mt('LON-CAPA can produce <b>CSV</b> files of this data or Excel files of the <b>Scores Summary</b> data.').'</p>'.$/;
 1109:     if ($chosen_output->{'base'} eq 'tries' && $total_columns > 255) {
 1110:         $r->print($too_many_cols_error_message);
 1111:         $request_aborted = 1;
 1112:     }
 1113:     if ($chosen_output->{'base'} eq 'scores' && $total_columns > 255) {
 1114:         $r->print($too_many_cols_error_message);
 1115:         $request_aborted = 1;
 1116:     }
 1117:     return if ($request_aborted);
 1118:     #
 1119:     #
 1120:     $excel_workbook = undef;
 1121:     $excel_sheet = undef;
 1122:     #
 1123:     $rows_output = 0;
 1124:     $cols_output = 0;
 1125:     #
 1126:     # Determine rows 
 1127:     my $header_row = $rows_output++;
 1128:     my $description_row = $rows_output++;
 1129:     my $notes_row = $rows_output++;
 1130:     $rows_output++;        # blank row
 1131:     my $summary_header_row;
 1132:     if ($chosen_output->{'summary_table'}) {
 1133:         $summary_header_row = $rows_output++;
 1134:         $rows_output+= scalar(@sequences);
 1135:         $rows_output++;
 1136:     }
 1137:     my $sequence_name_row = $rows_output++;
 1138:     my $resource_name_row = $rows_output++;
 1139:     my $maximum_data_row = $rows_output++;
 1140:     if (! $chosen_output->{'maximum_row'}) {
 1141:         $rows_output--;
 1142:     }
 1143:     my $first_data_row = $rows_output++;
 1144:     #
 1145:     # Create sheet
 1146:     ($excel_workbook,$filename,$format)=
 1147:         &Apache::loncommon::create_workbook($r);
 1148:     return if (! defined($excel_workbook));
 1149:     #
 1150:     # Add a worksheet
 1151:     my $sheetname = $env{'course.'.$env{'request.course.id'}.'.description'};
 1152:     $sheetname = &Apache::loncommon::clean_excel_name($sheetname);
 1153:     $excel_sheet = $excel_workbook->addworksheet($sheetname);
 1154:     #
 1155:     # Put the course description in the header
 1156:     $excel_sheet->write($header_row,$cols_output++,
 1157:                    $env{'course.'.$env{'request.course.id'}.'.description'},
 1158:                         $format->{'h1'});
 1159:     $cols_output += 3;
 1160:     #
 1161:     # Put a description of the sections listed
 1162:     my $sectionstring = '';
 1163:     my @Sections = &Apache::lonstatistics::get_selected_sections();
 1164:     $excel_sheet->write($header_row,$cols_output++,
 1165:                         &Apache::lonstatistics::section_and_enrollment_description('plaintext'),
 1166:                         $format->{'h3'});
 1167:     #
 1168:     # Put the date in there too
 1169:     $excel_sheet->write($header_row,$cols_output++,
 1170:                         'Compiled on '.localtime(time),$format->{'h3'});
 1171:     #
 1172:     $cols_output = 0;
 1173:     $excel_sheet->write($description_row,$cols_output++,
 1174:                         $chosen_output->{'shortdesc'},
 1175:                         $format->{'b'});
 1176:     #
 1177:     $cols_output = 0;
 1178:     $excel_sheet->write($notes_row,$cols_output++,
 1179:                         $chosen_output->{'non_html_notes'},
 1180:                         $format->{'i'});
 1181:     
 1182:     ##############################################
 1183:     # Output headings for the raw data
 1184:     ##############################################
 1185:     #
 1186:     # Add the student headers
 1187:     $cols_output = 0;
 1188:     foreach my $field (&get_student_fields_to_show()) {
 1189:         $excel_sheet->write($resource_name_row,$cols_output++,$field,
 1190:                             $format->{'bold'});
 1191:     }
 1192:     #
 1193:     # Add the remaining column headers
 1194:     my $total_formula_string = '=0';
 1195:     my $maximum_formula_string = '=0';
 1196:     foreach my $seq (@sequences) {
 1197:         my $symb = $seq->symb;
 1198:         $excel_sheet->write($sequence_name_row,,
 1199:                             $cols_output,$seq->compTitle,$format->{'bold'});
 1200:         # Determine starting cell
 1201:         $formula_data{$symb}->{'Excel:startcell'}=
 1202:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1203:             ($first_data_row,$cols_output);
 1204:         $formula_data{$symb}->{'Excel:startcol'}=$cols_output;
 1205:         my $count = 0;
 1206:         if ($chosen_output->{'every_problem'}) {
 1207:             # Put the names of the problems and parts into the sheet
 1208:             foreach my $res (&get_resources($navmap,$seq)) {
 1209:                 if (scalar(@{$res->parts}) > 1) {
 1210:                     foreach my $part (@{$res->parts}) {
 1211:                         $excel_sheet->write($resource_name_row,
 1212:                                             $cols_output++,
 1213:                                             $res->compTitle.' part '.$res->part_display($part),
 1214:                                             $format->{'bold'});
 1215:                         $count++;
 1216:                     }
 1217:                 } else {
 1218:                     $excel_sheet->write($resource_name_row,
 1219:                                         $cols_output++,
 1220:                                         $res->compTitle,$format->{'bold'});
 1221:                     $count++;
 1222:                 }
 1223:             }
 1224:         }
 1225:         # Determine ending cell
 1226:         if ($count <= 1) {
 1227:             $formula_data{$symb}->{'Excel:endcell'} = $formula_data{$symb}->{'Excel:startcell'};
 1228:             $formula_data{$symb}->{'Excel:endcol'}  = $formula_data{$symb}->{'Excel:startcol'};
 1229:         } else {
 1230:             $formula_data{$symb}->{'Excel:endcell'} = 
 1231:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1232:                 ($first_data_row,$cols_output-1);
 1233:             $formula_data{$symb}->{'Excel:endcol'} = $cols_output-1;
 1234:         }
 1235:         # Create the formula for summing up this sequence
 1236:         if (! exists($formula_data{$symb}->{'Excel:endcell'}) ||
 1237:             ! defined($formula_data{$symb}->{'Excel:endcell'})) {
 1238:             $formula_data{$symb}->{'Excel:endcell'} = $formula_data{$symb}->{'Excel:startcell'};
 1239:         }
 1240: 
 1241:         my $start = $formula_data{$symb}->{'Excel:startcell'};
 1242:         my $end = $formula_data{$symb}->{'Excel:endcell'};
 1243:         $formula_data{$symb}->{'Excel:sum'}= $excel_sheet->store_formula
 1244:             ("=IF(COUNT($start\:$end),SUM($start\:$end),\"\")");
 1245:         # Determine cell the score is held in
 1246:         $formula_data{$symb}->{'Excel:scorecell'} = 
 1247:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1248:             ($first_data_row,$cols_output);
 1249:         $formula_data{$symb}->{'Excel:scorecol'}=$cols_output;
 1250:         if ($chosen_output->{'base'} eq 'parts correct total') {
 1251:             $excel_sheet->write($resource_name_row,$cols_output++,
 1252:                                 'parts correct',
 1253:                                 $format->{'bold'});
 1254:         } elsif ($chosen_output->{'sequence_sum'}) {
 1255:             if ($chosen_output->{'correct'}) {
 1256:                 # Only reporting the number correct, so do not call it score
 1257:                 $excel_sheet->write($resource_name_row,$cols_output++,
 1258:                                     'sum',
 1259:                                     $format->{'bold'});
 1260:             } else {
 1261:                 $excel_sheet->write($resource_name_row,$cols_output++,
 1262:                                     'score',
 1263:                                     $format->{'bold'});
 1264:             }
 1265:         }
 1266:         #
 1267:         $total_formula_string.='+'.
 1268:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1269:             ($first_data_row,$cols_output-1);
 1270:         if ($chosen_output->{'sequence_max'}) {
 1271:             $excel_sheet->write($resource_name_row,$cols_output,
 1272:                                 'maximum',
 1273:                                 $format->{'bold'});
 1274:             $formula_data{$symb}->{'Excel:maxcell'} = 
 1275:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1276:                 ($first_data_row,$cols_output);
 1277:             $formula_data{$symb}->{'Excel:maxcol'}=$cols_output;
 1278:             $maximum_formula_string.='+'.
 1279:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1280:                 ($first_data_row,$cols_output);
 1281:             $cols_output++;
 1282: 
 1283:         }
 1284:     }
 1285:     if ($chosen_output->{'grand_total'}) {
 1286:         $excel_sheet->write($resource_name_row,$cols_output++,'Total',
 1287:                             $format->{'bold'});
 1288:     }
 1289:     if ($chosen_output->{'grand_maximum'}) {
 1290:         $excel_sheet->write($resource_name_row,$cols_output++,'Max. Total',
 1291:                             $format->{'bold'});
 1292:     }
 1293:     $total_formula = $excel_sheet->store_formula($total_formula_string);
 1294:     $maximum_formula = $excel_sheet->store_formula($maximum_formula_string);
 1295:     ##############################################
 1296:     # Output a row for MAX, if appropriate
 1297:     ##############################################
 1298:     if ($chosen_output->{'maximum_row'}) {
 1299:         $cols_output = 0;
 1300:         foreach my $field (&get_student_fields_to_show()) {
 1301:             if ($field eq 'username' || $field eq 'fullname' || 
 1302:                 $field eq 'id') {
 1303:                 $excel_sheet->write($maximum_data_row,$cols_output++,'Maximum',
 1304:                                     $format->{'bold'});
 1305:             } else {
 1306:                 $excel_sheet->write($maximum_data_row,$cols_output++,'');
 1307:             }
 1308:         }
 1309:         #
 1310:         # Add the maximums for each sequence or assessment
 1311:         my %total_cell_translation;
 1312:         my %maximum_cell_translation;
 1313:         foreach my $seq (@sequences) {
 1314:             my $symb = $seq->symb;
 1315:             $cols_output=$formula_data{$symb}->{'Excel:startcol'};
 1316:             $total_cell_translation{$formula_data{$symb}->{'Excel:scorecell'}}=
 1317:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1318:                 ($maximum_data_row,$formula_data{$symb}->{'Excel:scorecol'});
 1319:             $maximum_cell_translation{$formula_data{$symb}->{'Excel:maxcell'}}=
 1320:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1321:                 ($maximum_data_row,$formula_data{$symb}->{'Excel:maxcol'});
 1322:             my $weight;
 1323:             my $max = 0;
 1324:             foreach my $resource (&get_resources($navmap,$seq)) {
 1325:                 foreach my $part (@{$resource->parts}){
 1326:                     $weight = 1;
 1327:                     if ($chosen_output->{'scores'}) {
 1328:                         $weight = &Apache::lonnet::EXT
 1329:                             ('resource.'.$part.'.weight',$resource->symb,
 1330:                              undef,undef,undef);
 1331:                         if (!defined($weight) || ($weight eq '')) { 
 1332:                             $weight=1;
 1333:                         }
 1334:                     }
 1335:                     if ($chosen_output->{'scores'} &&
 1336:                         $chosen_output->{'every_problem'}) {
 1337:                         $excel_sheet->write($maximum_data_row,$cols_output++,
 1338:                                             $weight);
 1339:                     }
 1340:                     $max += $weight;
 1341:                 }
 1342:             } 
 1343:             #
 1344:             if ($chosen_output->{'sequence_sum'} && 
 1345:                 $chosen_output->{'every_problem'}) {
 1346: 		my %replaceCells=
 1347: 		    ('^'.$formula_data{$symb}->{'Excel:startcell'}.':'.
 1348: 		         $formula_data{$symb}->{'Excel:endcell'}.'$' =>
 1349: 		     &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($maximum_data_row,$formula_data{$symb}->{'Excel:startcol'}).':'.
 1350: 		     &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($maximum_data_row,$formula_data{$symb}->{'Excel:endcol'}));
 1351:                 $excel_sheet->repeat_formula($maximum_data_row,$cols_output++,
 1352:                                              $formula_data{$symb}->{'Excel:sum'},undef,
 1353: 					     %replaceCells, %replaceCells);
 1354: 			
 1355:             } elsif ($chosen_output->{'sequence_sum'}) {
 1356:                 $excel_sheet->write($maximum_data_row,$cols_output++,$max);
 1357:             }
 1358:             if ($chosen_output->{'sequence_max'}) {
 1359:                 $excel_sheet->write($maximum_data_row,$cols_output++,$max);
 1360:             }
 1361:             #
 1362:         }
 1363:         if ($chosen_output->{'grand_total'}) {
 1364:             $excel_sheet->repeat_formula($maximum_data_row,$cols_output++,
 1365:                                          $total_formula,undef,
 1366:                                          %total_cell_translation);
 1367:         }
 1368:         if ($chosen_output->{'grand_maximum'}) {
 1369:             $excel_sheet->repeat_formula($maximum_data_row,$cols_output++,
 1370:                                          $maximum_formula,undef,
 1371:                                          %maximum_cell_translation);
 1372:         }
 1373:     } # End of MAXIMUM row output  if ($chosen_output->{'maximum_row'}) {
 1374:     $rows_output = $first_data_row;
 1375:     ##############################################
 1376:     # Output summary table, which actually is above the sequence name row.
 1377:     ##############################################
 1378:     if ($chosen_output->{'summary_table'}) {
 1379:         $cols_output = 0;
 1380:         $excel_sheet->write($summary_header_row,$cols_output++,
 1381:                             'Summary Table',$format->{'bold'});
 1382:         if ($chosen_output->{'maximum_row'}) {
 1383:             $excel_sheet->write($summary_header_row,$cols_output++,
 1384:                                 'Maximum',$format->{'bold'});
 1385:         }
 1386:         $excel_sheet->write($summary_header_row,$cols_output++,
 1387:                             'Average',$format->{'bold'});
 1388:         $excel_sheet->write($summary_header_row,$cols_output++,
 1389:                             'Median',$format->{'bold'});
 1390:         $excel_sheet->write($summary_header_row,$cols_output++,
 1391:                             'Std Dev',$format->{'bold'});
 1392:         my $row = $summary_header_row+1;
 1393:         foreach my $seq (@sequences) {
 1394:             my $symb = $seq->symb;
 1395:             $cols_output = 0;
 1396:             $excel_sheet->write($row,$cols_output++,
 1397:                                 $seq->compTitle,
 1398:                                 $format->{'bold'});
 1399:             if ($chosen_output->{'maximum_row'}) {
 1400:                 $excel_sheet->write
 1401:                     ($row,$cols_output++,
 1402:                      '='.
 1403:                      &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1404:                      ($maximum_data_row,$formula_data{$symb}->{'Excel:scorecol'})
 1405:                      );
 1406:             }
 1407:             my $range = 
 1408:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1409:                 ($first_data_row,$formula_data{$symb}->{'Excel:scorecol'}).
 1410:                 ':'.
 1411:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1412:                 ($first_data_row+$num_students-1,$formula_data{$symb}->{'Excel:scorecol'});
 1413:             $excel_sheet->write($row,$cols_output++,
 1414:                                 '=AVERAGE('.$range.')');
 1415:             $excel_sheet->write($row,$cols_output++,
 1416:                                 '=MEDIAN('.$range.')');
 1417:             $excel_sheet->write($row,$cols_output++,
 1418:                                 '=STDEV('.$range.')');
 1419:             $row++;
 1420:         }
 1421:     }
 1422:     ##############################################
 1423:     #   Take care of non-excel initialization
 1424:     ##############################################
 1425:     #
 1426:     # Let the user know what we are doing
 1427:     my $studentcount = scalar(@Apache::lonstatistics::Students); 
 1428:     if ($env{'form.SelectedStudent'}) {
 1429:         $studentcount = '1';
 1430:     }
 1431:     if ($studentcount > 1) {
 1432:         $r->print('<h1>'.&mt('Compiling Excel spreadsheet for [_1] students',
 1433:                              $studentcount)."</h1>\n");
 1434:     } else {
 1435:         $r->print('<h1>'.
 1436:                   &mt('Compiling Excel spreadsheet for 1 student').
 1437:                   "</h1>\n");
 1438:     }
 1439:     $r->rflush();
 1440:     #
 1441:     # Initialize progress window
 1442:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1443:         ($r,'Excel File Compilation Status',
 1444:          'Excel File Compilation Progress', $studentcount,
 1445:          'inline',undef,'Statistics','stats_status');
 1446:     #
 1447:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 1448:                                           'Processing first student');
 1449:     return;
 1450: }
 1451: 
 1452: sub excel_outputstudent {
 1453:     my ($r,$student) = @_;
 1454:     if ($request_aborted || ! defined($navmap) || ! defined($excel_sheet)) {
 1455:         return;
 1456:     }
 1457:     $cols_output=0;
 1458:     #
 1459:     # Write out student data
 1460:     my @to_show = &get_student_fields_to_show();
 1461:     foreach my $field (@to_show) {
 1462:         my $value = $student->{$field};
 1463:         if ($field eq 'comments') {
 1464:             $value = &Apache::lonmsgdisplay::retrieve_instructor_comments
 1465:                 ($student->{'username'},$student->{'domain'});
 1466:         }
 1467:         $excel_sheet->write($rows_output,$cols_output++,$value);
 1468:     }
 1469:     #
 1470:     # Get student assessment data
 1471:     my %StudentsData;
 1472:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
 1473:                                                         $student->{'domain'},
 1474:                                                         undef,
 1475:                                                    $env{'request.course.id'});
 1476:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 1477:         %StudentsData = @tmp;
 1478:     }
 1479:     #
 1480:     # Write out sequence scores and totals data
 1481:     my %total_cell_translation;
 1482:     my %maximum_cell_translation;
 1483:     foreach my $seq (@sequences) {
 1484:         my $symb = $seq->symb;
 1485:         $cols_output = $formula_data{$symb}->{'Excel:startcol'};
 1486:         # Keep track of cells to translate in total cell
 1487:         $total_cell_translation{$formula_data{$symb}->{'Excel:scorecell'}} = 
 1488:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1489:                         ($rows_output,$formula_data{$symb}->{'Excel:scorecol'});
 1490:         # and maximum cell
 1491:         $maximum_cell_translation{$formula_data{$symb}->{'Excel:maxcell'}} = 
 1492:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1493:             ($rows_output,$formula_data{$symb}->{'Excel:maxcol'});
 1494:         #
 1495:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
 1496:         if ($chosen_output->{'tries'} || $chosen_output->{'correct'}){
 1497:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1498:                 &student_tries_on_sequence($student,\%StudentsData,
 1499:                                            $navmap,$seq,'no');
 1500:         } else {
 1501:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1502:                 &student_performance_on_sequence($student,\%StudentsData,
 1503:                                                  $navmap,$seq,'no',
 1504:                                                  $chosen_output->{ignore_weight});
 1505:         } 
 1506:         if ($chosen_output->{'every_problem'}) {
 1507:             if ($chosen_output->{'correct'}) {
 1508:                 # only indiciate if each item is correct or not
 1509:                 foreach my $value (@$rawdata) {
 1510:                     # positive means correct, 0 or negative means
 1511:                     # incorrect
 1512:                     $value = $value > 0 ? 1 : 0;
 1513:                     $excel_sheet->write($rows_output,$cols_output++,$value);
 1514:                 }
 1515:             } else {
 1516:                 foreach my $value (@$rawdata) {
 1517:                     if ($score eq ' ' || !defined($value)) {
 1518:                         $cols_output++;
 1519:                     } else {                        
 1520:                         $excel_sheet->write($rows_output,$cols_output++,
 1521:                                             $value);
 1522:                     }
 1523:                 }
 1524:             }
 1525:         }
 1526:         if ($chosen_output->{'sequence_sum'} && 
 1527:             $chosen_output->{'every_problem'}) {
 1528:             # Write a formula for the sum of this sequence
 1529:             my %replaceCells=
 1530: 		('^'.$formula_data{$symb}->{'Excel:startcell'}.':'.$formula_data{$symb}->{'Excel:endcell'}.'$'
 1531: 		 => 
 1532: 		 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($rows_output,$formula_data{$symb}->{'Excel:startcol'}).':'.
 1533: 		 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($rows_output,$formula_data{$symb}->{'Excel:endcol'})
 1534: 		 );
 1535:             # The undef is for the format	    
 1536: 	    $excel_sheet->repeat_formula($rows_output,$cols_output++,
 1537: 					 $formula_data{$symb}->{'Excel:sum'},undef,
 1538: 					 %replaceCells, %replaceCells);
 1539:         } elsif ($chosen_output->{'sequence_sum'}) {
 1540:             if ($score eq ' ') {
 1541:                 $cols_output++;
 1542:             } else {
 1543:                 $excel_sheet->write($rows_output,$cols_output++,$score);
 1544:             }
 1545:         }
 1546:         if ($chosen_output->{'sequence_max'}) {
 1547:             $excel_sheet->write($rows_output,$cols_output++,$seq_max);
 1548:         }
 1549:     }
 1550:     #
 1551:     if ($chosen_output->{'grand_total'}) {
 1552:         $excel_sheet->repeat_formula($rows_output,$cols_output++,
 1553:                                      $total_formula,undef,
 1554:                                      %total_cell_translation);
 1555:     }
 1556:     if ($chosen_output->{'grand_maximum'}) {
 1557:         $excel_sheet->repeat_formula($rows_output,$cols_output++,
 1558:                                      $maximum_formula,undef,
 1559:                                      %maximum_cell_translation);
 1560:     }
 1561:     #
 1562:     # Bookkeeping
 1563:     $rows_output++; 
 1564:     $cols_output=0;
 1565:     #
 1566:     # Update the progress window
 1567:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 1568:     return;
 1569: }
 1570: 
 1571: sub excel_finish {
 1572:     my ($r) = @_;
 1573:     if ($request_aborted || ! defined($navmap) || ! defined($excel_sheet)) {
 1574: 	&excel_cleanup();
 1575:         return;
 1576:     }
 1577:     #
 1578:     # Write the excel file
 1579:     $excel_workbook->close();
 1580:     #
 1581:     # Close the progress window
 1582:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1583:     #
 1584:     # Tell the user where to get their excel file
 1585:     $r->print('<br />'.
 1586:               '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
 1587:     $r->rflush();
 1588:     &excel_cleanup();
 1589:     return;
 1590: }
 1591: 
 1592: }
 1593: #######################################################
 1594: #######################################################
 1595: 
 1596: =pod
 1597: 
 1598: =head2 CSV output routines
 1599: 
 1600: =item &csv_initialize($r)
 1601: 
 1602: =item &csv_outputstudent($r,$student)
 1603: 
 1604: =item &csv_finish($r)
 1605: 
 1606: =cut
 1607: 
 1608: #######################################################
 1609: #######################################################
 1610: {
 1611: 
 1612: my $outputfile;
 1613: my $filename;
 1614: my $request_aborted;
 1615: my %prog_state; # progress window state
 1616: my $navmap;
 1617: my @sequences;
 1618: 
 1619: sub csv_cleanup {
 1620:     undef($outputfile);
 1621:     undef($filename);
 1622:     undef($request_aborted);
 1623:     undef(%prog_state);
 1624:     #
 1625:     undef($navmap);
 1626:     undef(@sequences);
 1627: }
 1628: 
 1629: sub csv_initialize{
 1630:     my ($r) = @_;
 1631: 
 1632:     &csv_cleanup();
 1633:     ($navmap,@sequences) = 
 1634:         &Apache::lonstatistics::selected_sequences_with_assessments();
 1635:     if (! ref($navmap)) {
 1636:         # Unable to get data, so bail out
 1637:         $r->print("<h3>".
 1638:                   &mt('Unable to retrieve course information.').
 1639:                   '</h3>');
 1640:     }
 1641:     #
 1642:     # Deal with unimplemented requests
 1643:     $request_aborted = undef;
 1644:     if ($chosen_output->{'base'} =~ /final table/) {
 1645:         $r->print(<<END);
 1646: <h2>Unable to Complete Request</h2>
 1647: <p>
 1648: The <b>Summary Table (Scores)</b> option is not available for non-HTML output.
 1649: </p>
 1650: END
 1651:        $request_aborted = 1;
 1652:     }
 1653:     return if ($request_aborted);
 1654:     #
 1655:     # Initialize progress window
 1656:     my $studentcount = scalar(@Apache::lonstatistics::Students);
 1657:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1658:         ($r,'CSV File Compilation Status',
 1659:          'CSV File Compilation Progress', $studentcount,
 1660:          'inline',undef,'Statistics','stats_status');
 1661:     #
 1662:     # Open a file
 1663:     ($outputfile,$filename) = &Apache::loncommon::create_text_file($r,'csv');
 1664:     if (! defined($outputfile)) { return ''; }
 1665:     #
 1666:     # Datestamp
 1667:     my $description = $env{'course.'.$env{'request.course.id'}.'.description'};
 1668:     print $outputfile '"'.&Apache::loncommon::csv_translate($description).'",'.
 1669:         '"'.&Apache::loncommon::csv_translate(scalar(localtime(time))).'"'.
 1670:             "\n";
 1671:     print $outputfile '"'.
 1672:         &Apache::loncommon::csv_translate
 1673:         (&Apache::lonstatistics::section_and_enrollment_description()).
 1674:         '"'."\n";
 1675:     foreach my $item ('shortdesc','non_html_notes') {
 1676:         next if (! exists($chosen_output->{$item}));
 1677:         print $outputfile 
 1678:             '"'.&Apache::loncommon::csv_translate($chosen_output->{$item}).'"'.
 1679:             "\n";
 1680:     }
 1681:     #
 1682:     # Print out the headings
 1683:     my $sequence_row = '';
 1684:     my $resource_row = undef;
 1685:     foreach my $field (&get_student_fields_to_show()) {
 1686:         $sequence_row .='"",';
 1687:         $resource_row .= '"'.&Apache::loncommon::csv_translate($field).'",';
 1688:     }
 1689:     foreach my $seq (@sequences) {
 1690:         $sequence_row .= '"'.
 1691:             &Apache::loncommon::csv_translate($seq->compTitle).'",';
 1692:         my $count = 0;
 1693:         if ($chosen_output->{'every_problem'}) {
 1694:             foreach my $res (&get_resources($navmap,$seq)) {
 1695:                 if (scalar(@{$res->parts}) < 1) {
 1696:                     next;
 1697:                 }
 1698:                 foreach my $part (@{$res->parts}) {
 1699:                     $resource_row .= '"'.
 1700:                         &Apache::loncommon::csv_translate
 1701:                         ($res->compTitle.', Part '.$res->part_display($part)).'",';
 1702:                     $count++;
 1703:                 }
 1704:             }
 1705:         }
 1706:         $sequence_row.='"",'x$count;
 1707:         if ($chosen_output->{'sequence_sum'}) {
 1708:             if($chosen_output->{'correct'}) {
 1709:                 $resource_row .= '"sum",';
 1710:             } else {
 1711:                 $resource_row .= '"score",';
 1712:             }
 1713:         }
 1714:         if ($chosen_output->{'sequence_max'}) {
 1715:             $sequence_row.= '"",';
 1716:             $resource_row .= '"maximum possible",';
 1717:         }
 1718:     }
 1719:     if ($chosen_output->{'grand_total'}) {
 1720:         $sequence_row.= '"",';
 1721:         $resource_row.= '"Total",';
 1722:     } 
 1723:     if ($chosen_output->{'grand_maximum'}) {
 1724:         $sequence_row.= '"",';
 1725:         $resource_row.= '"Maximum",';
 1726:     } 
 1727:     chomp($sequence_row);
 1728:     chomp($resource_row);
 1729:     print $outputfile $sequence_row."\n";
 1730:     print $outputfile $resource_row."\n";
 1731:     return;
 1732: }
 1733: 
 1734: sub csv_outputstudent {
 1735:     my ($r,$student) = @_;
 1736:     if ($request_aborted || ! defined($navmap) || ! defined($outputfile)) {
 1737:         return;
 1738:     }
 1739:     my $Str = '';
 1740:     #
 1741:     # Output student fields
 1742:     my @to_show = &get_student_fields_to_show();
 1743:     foreach my $field (@to_show) {
 1744:         my $value = $student->{$field};
 1745:         if ($field eq 'comments') {
 1746:             $value = &Apache::lonmsgdisplay::retrieve_instructor_comments
 1747:                 ($student->{'username'},$student->{'domain'});
 1748:         }        
 1749:         $Str .= '"'.&Apache::loncommon::csv_translate($value).'",';
 1750:     }
 1751:     #
 1752:     # Get student assessment data
 1753:     my %StudentsData;
 1754:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
 1755:                                                         $student->{'domain'},
 1756:                                                         undef,
 1757:                                                    $env{'request.course.id'});
 1758:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 1759:         %StudentsData = @tmp;
 1760:     }
 1761:     #
 1762:     # Output performance data
 1763:     my $total = 0;
 1764:     my $maximum = 0;
 1765:     foreach my $seq (@sequences) {
 1766:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
 1767:         if ($chosen_output->{'tries'}){
 1768:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1769:                 &student_tries_on_sequence($student,\%StudentsData,
 1770:                                            $navmap,$seq,'no');
 1771:         } else {
 1772:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1773:                 &student_performance_on_sequence($student,\%StudentsData,
 1774:                                                  $navmap,$seq,'no',
 1775:                                                  $chosen_output->{ignore_weight});
 1776:         }
 1777:         if ($chosen_output->{'every_problem'}) {
 1778:             if ($chosen_output->{'correct'}) {
 1779:                 $score = 0;
 1780:                 # Deal with number of parts correct data
 1781:                 $Str .= '"'.join('","',( map { if ($_>0) { 
 1782:                                                    $score += 1;
 1783:                                                    1; 
 1784:                                                } else { 
 1785:                                                    0; 
 1786:                                                }
 1787:                                              } @$rawdata)).'",';
 1788:             } else {
 1789:                 $Str .= '"'.join('","',(@$rawdata)).'",';
 1790:             }
 1791:         }
 1792:         if ($chosen_output->{'sequence_sum'}) {
 1793:             $Str .= '"'.$score.'",';
 1794:         } 
 1795:         if ($chosen_output->{'sequence_max'}) {
 1796:             $Str .= '"'.$seq_max.'",';
 1797:         }
 1798:         $total+=$score;
 1799:         $maximum += $seq_max;
 1800:     }
 1801:     if ($chosen_output->{'grand_total'}) {
 1802:         $Str .= '"'.$total.'",';
 1803:     }
 1804:     if ($chosen_output->{'grand_maximum'}) {
 1805:         $Str .= '"'.$maximum.'",';
 1806:     }
 1807:     chop($Str);
 1808:     $Str .= "\n";
 1809:     print $outputfile $Str;
 1810:     #
 1811:     # Update the progress window
 1812:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 1813:     return;
 1814: }
 1815: 
 1816: sub csv_finish {
 1817:     my ($r) = @_;
 1818:     if ($request_aborted || ! defined($navmap) || ! defined($outputfile)) {
 1819: 	&csv_cleanup();
 1820:         return;
 1821:     }
 1822:     close($outputfile);
 1823:     #
 1824:     # Close the progress window
 1825:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1826:     #
 1827:     # Tell the user where to get their csv file
 1828:     $r->print('<br />'.
 1829:               '<a href="'.$filename.'">'.&mt('Your CSV file.').'</a>'."\n");
 1830:     $r->rflush();
 1831:     &csv_cleanup();
 1832:     return;
 1833:     
 1834: }
 1835: 
 1836: }
 1837: 
 1838: # This function will return an HTML string including a star, with
 1839: # a mouseover popup showing the "real" value. An optional second
 1840: # argument lets you show something other than a star.
 1841: sub show_star {
 1842:     my $popup = shift;
 1843:     my $symbol = shift || '*';
 1844:     # Escape the popup for JS.
 1845:     $popup =~ s/([^-a-zA-Z0-9:;,._ ()|!\/?=&*])/'\\' . sprintf("%lo", ord($1))/ge;
 1846:     
 1847:     return "<span class=\"LC_chrt_popup_exists\" onmouseover='popup_score(this, \"$popup\");return false;' onmouseout='popdown_score();return false;'>$symbol</span>";
 1848: }
 1849: 
 1850: #######################################################
 1851: #######################################################
 1852: 
 1853: =pod
 1854: 
 1855: =item &StudentTriesOnSequence()
 1856: 
 1857: Inputs:
 1858: 
 1859: =over 4
 1860: 
 1861: =item $student
 1862: 
 1863: =item $studentdata Hash ref to all student data
 1864: 
 1865: =item $seq Hash ref, the sequence we are working on
 1866: 
 1867: =item $links if defined we will output links to each resource.
 1868: 
 1869: =back
 1870: 
 1871: =cut
 1872: 
 1873: #######################################################
 1874: #######################################################
 1875: sub student_tries_on_sequence {
 1876:     my ($student,$studentdata,$navmap,$seq,$links) = @_;
 1877:     $links = 'no' if (! defined($links));
 1878:     my $Str = '';
 1879:     my ($sum,$max) = (0,0);
 1880:     my $performance_length = 0;
 1881:     my @TriesData = ();
 1882:     my $tries;
 1883:     my $hasdata = 0; # flag - true if the student has any data on the sequence
 1884:     foreach my $resource (&get_resources($navmap,$seq)) {
 1885:         my $resource_data = $studentdata->{$resource->symb};
 1886:         my $value = '';
 1887:         foreach my $partnum (@{$resource->parts()}) {
 1888:             $tries = undef;
 1889:             $max++;
 1890:             $performance_length++;
 1891:             my $symbol = ' '; # default to space
 1892:             #
 1893:             my $awarded = 0;
 1894:             if (exists($resource_data->{'resource.'.$partnum.'.awarded'})) {
 1895:                 $awarded = $resource_data->{'resource.'.$partnum.'.awarded'};
 1896:                 $awarded = 0 if (! $awarded);
 1897:             }
 1898:             #
 1899:             my $status = '';
 1900:             if (exists($resource_data->{'resource.'.$partnum.'.solved'})) {
 1901:                 $status = $resource_data->{'resource.'.$partnum.'.solved'};
 1902:             }
 1903:             #
 1904:             my $tries = 0;
 1905:             if(exists($resource_data->{'resource.'.$partnum.'.tries'})) {
 1906:                 $tries = $resource_data->{'resource.'.$partnum.'.tries'};
 1907:                 $hasdata =1;
 1908:             }
 1909:             #
 1910:             if ($awarded > 0) {
 1911:                 # The student has gotten the problem correct to some degree
 1912:                 if ($status eq 'excused') {
 1913:                     $symbol = 'x';
 1914:                     $max--;
 1915:                 } elsif ($status eq 'correct_by_override' && !$resource->is_task()) {
 1916:                     $symbol = '+';
 1917:                     $sum++;
 1918:                 } elsif ($tries > 0) {
 1919:                     if ($tries > 9) {
 1920:                         $symbol = show_star($tries);
 1921:                     } else {
 1922:                         $symbol = $tries;
 1923:                     }
 1924:                     $sum++;
 1925:                 } else {
 1926:                     $symbol = '+';
 1927:                     $sum++;
 1928:                 }
 1929:             } else {
 1930:                 # The student has the problem incorrect or it is ungraded
 1931:                 if ($status eq 'excused') {
 1932:                     $symbol = 'x';
 1933:                     $max--;
 1934:                 } elsif ($status eq 'incorrect_by_override') {
 1935:                     $symbol = '-';
 1936:                 } elsif ($status eq 'ungraded_attempted') {
 1937:                     $symbol = 'u';
 1938:                 } elsif ($status eq 'incorrect_attempted' ||
 1939:                          $tries > 0)  {
 1940:                     $symbol = '.';
 1941:                 } else {
 1942:                     # Problem is wrong and has not been attempted.
 1943:                     $symbol=' ';
 1944:                 }
 1945:             }
 1946:             #
 1947:             if (! defined($tries)) {
 1948:                 $tries = 0;
 1949:             }
 1950:             if ($status =~ /^(incorrect|ungraded)/) {
 1951:                 # Bug 3390: show '-' for tries on incorrect problems 
 1952:                 # (csv & excel only)
 1953:                 push(@TriesData,-$tries);
 1954:             } else {
 1955:                 push (@TriesData,$tries);
 1956:             }
 1957:             #
 1958:             if ( ($links eq 'yes' && $symbol ne ' ') ||
 1959:                  ($links eq 'all')) {
 1960:                 my $link = '/adm/grades'.
 1961:                     '?symb='.&escape($resource->shown_symb).
 1962:                         '&student='.$student->{'username'}.
 1963:                             '&userdom='.$student->{'domain'}.
 1964:                                 '&command=submission';
 1965:                 $symbol = &link($symbol, $link);
 1966:             }
 1967:             $value .= $symbol;
 1968:         }
 1969:         $Str .= $value;
 1970:     }
 1971:     if ($seq->randompick()) {
 1972:         $max = $seq->randompick();
 1973:     }
 1974:     if (! $hasdata && $sum == 0) {
 1975:         $sum = ' ';
 1976:     }
 1977:     return ($Str,$performance_length,$sum,$max,\@TriesData);
 1978: }
 1979: 
 1980: =pod
 1981: 
 1982: =item &link
 1983: 
 1984: Inputs:
 1985: 
 1986: =over 4
 1987: 
 1988: =item $text
 1989: 
 1990: =item $target
 1991: 
 1992: =back
 1993: 
 1994: Takes the text and creates a link to the $text that honors
 1995: the value of 'new window' if clicked on, but uses a real 
 1996: 'href' so middle and right clicks still work.
 1997: 
 1998: $target and $text are assumed to be already correctly escaped; i.e., it
 1999: can be dumped out directly into the output stream as-is.
 2000: 
 2001: =cut
 2002: 
 2003: sub link {
 2004:     my ($text,$target) = @_;
 2005:     return 
 2006:         "<a href='$target' onclick=\"t=this.href;if(new_window)"
 2007:         ."{window.open(t)}else{return void(window."
 2008:         ."location=t)};return false;\">$text</a>";
 2009: }
 2010: 
 2011: #######################################################
 2012: #######################################################
 2013: 
 2014: =pod
 2015: 
 2016: =item &student_performance_on_sequence
 2017: 
 2018: Inputs:
 2019: 
 2020: =over 4
 2021: 
 2022: =item $student
 2023: 
 2024: =item $studentdata Hash ref to all student data
 2025: 
 2026: =item $seq Hash ref, the sequence we are working on
 2027: 
 2028: =item $links if defined we will output links to each resource.
 2029: 
 2030: =back
 2031: 
 2032: =cut
 2033: 
 2034: #######################################################
 2035: #######################################################
 2036: sub student_performance_on_sequence {
 2037:     my ($student,$studentdata,$navmap,$seq,$links,$awarded_only) = @_;
 2038:     $links = 'no' if (! defined($links));
 2039:     my $Str = ''; # final result string
 2040:     my ($score,$max) = (0,0);
 2041:     my $performance_length = 0;
 2042:     my $symbol;
 2043:     my @ScoreData = ();
 2044:     my $partscore;
 2045:     my $hasdata = 0; # flag, 0 if there were no submissions on the sequence
 2046:     foreach my $resource (&get_resources($navmap,$seq)) {
 2047:         my $symb = $resource->symb;
 2048:         my $resource_data = $studentdata->{$symb};
 2049:         foreach my $part (@{$resource->parts()}) {
 2050:             $partscore = undef;
 2051:             my $weight;
 2052:             if (!$awarded_only){
 2053:                 $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
 2054:                                                $symb,
 2055:                                                $student->{'domain'},
 2056:                                                $student->{'username'},
 2057:                                                $student->{'section'});
 2058:             }
 2059:             if (!defined($weight) || ($weight eq '')) { 
 2060:                 $weight=1;
 2061:             }
 2062:             #
 2063:             $max += $weight; # see the 'excused' branch below...
 2064:             $performance_length++; # one character per part
 2065:             $symbol = ' '; # default to space
 2066:             #
 2067:             my $awarded;
 2068:             if (exists($resource_data->{'resource.'.$part.'.awarded'})) {
 2069:                 $awarded = $resource_data->{'resource.'.$part.'.awarded'};
 2070:                 $awarded = 0 if (! $awarded);
 2071:                 $hasdata = 1;
 2072:             }
 2073:             #
 2074:             $partscore = &Apache::grades::compute_points($weight,$awarded);
 2075:             if (! defined($awarded)) {
 2076:                 $partscore = undef;
 2077:             }
 2078:             $score += $partscore;
 2079:             $symbol = $partscore; 
 2080:             if (abs($symbol - sprintf("%.0f",$symbol)) < 0.001) {
 2081:                 $symbol = sprintf("%.0f",$symbol);
 2082:             }
 2083:             if (length($symbol) > 1) {
 2084:                 $symbol = show_star($symbol);
 2085:             }
 2086:             if (exists($resource_data->{'resource.'.$part.'.solved'}) &&
 2087:                 $resource_data->{'resource.'.$part.'.solved'} ne '') {
 2088:                 my $status = $resource_data->{'resource.'.$part.'.solved'};
 2089:                 if ($status eq 'excused') {
 2090:                     $symbol = 'x';
 2091:                     $max -= $weight; # Do not count 'excused' problems.
 2092:                 } elsif ($status eq 'ungraded_attempted') {
 2093:                     $symbol = 'u';
 2094:                 }
 2095:                 $hasdata = 1;
 2096:             } elsif ($resource_data->{'resource.'.$part.'.award'} eq 'DRAFT') {
 2097:                 $symbol = 'd';
 2098:                 $hasdata = 1;
 2099:             } elsif (!exists($resource_data->{'resource.'.$part.'.awarded'})){
 2100:                 # Unsolved.  Did they try?
 2101:                 if (exists($resource_data->{'resource.'.$part.'.tries'})){
 2102:                     $symbol = '.';
 2103:                     $hasdata = 1;
 2104:                 } else {
 2105:                     $symbol = ' ';
 2106:                 }
 2107:             }
 2108:             #
 2109:             if (! defined($partscore)) {
 2110:                 $partscore = $symbol;
 2111:             }
 2112:             push (@ScoreData,$partscore);
 2113:             #
 2114:             if ( ($links eq 'yes' && $symbol ne ' ') || ($links eq 'all')) {
 2115:                 my $link = '/adm/grades' .
 2116:                     '?symb='.&escape($resource->shown_symb).
 2117:                     '&student='.$student->{'username'}.
 2118:                     '&userdom='.$student->{'domain'}.
 2119:                     '&command=submission';
 2120:                 $symbol = &link($symbol, $link);
 2121:             }
 2122:             $Str .= $symbol;
 2123:         }
 2124:     }
 2125:     if (! $hasdata && $score == 0) {
 2126:         $score = ' ';
 2127:     }
 2128:     return ($Str,$performance_length,$score,$max,\@ScoreData);
 2129: }
 2130: 
 2131: #######################################################
 2132: #######################################################
 2133: 
 2134: =pod
 2135: 
 2136: =item &CreateLegend()
 2137: 
 2138: This function returns a formatted string containing the legend for the
 2139: chart.  The legend describes the symbols used to represent grades for
 2140: problems.
 2141: 
 2142: =cut
 2143: 
 2144: #######################################################
 2145: #######################################################
 2146: sub CreateLegend {
 2147:     my $Str = "<p><pre>".
 2148:               " digit score or number of tries to get correct ".
 2149:               "   *  correct by student in more than 9 tries\n".
 2150: 	      "   +  correct by hand grading or override\n".
 2151:               "   -  incorrect by override\n".
 2152: 	      "   .  incorrect attempted\n".
 2153: 	      "   u  ungraded attempted\n".
 2154:               "   d  draft answer saved but not submitted\n".
 2155:               "      not attempted (blank field)\n".
 2156: 	      "   x  excused".
 2157:               "</pre><p>";
 2158:     return $Str;
 2159: }
 2160: 
 2161: #######################################################
 2162: #######################################################
 2163: 
 2164: =pod 
 2165: 
 2166: =back
 2167: 
 2168: =cut
 2169: 
 2170: #######################################################
 2171: #######################################################
 2172: 
 2173: 1;
 2174: 
 2175: __END__

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