File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.169.2.2: download - view: text, annotated - select for diffs
Sun Dec 16 17:11:23 2012 UTC (11 years, 7 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.170, 1.171

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

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