File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.135: download - view: text, annotated - select for diffs
Tue Mar 21 16:49:59 2006 UTC (18 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- <label>

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

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