File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.112: download - view: text, annotated - select for diffs
Fri Feb 25 02:37:49 2005 UTC (19 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Reworking to use navmaps directly.  It compiles.  Most statistics pages
will not load. chart works for html output only, although the columns are
off and all sequences are selected regardless of what you say.  In short,
it needs work.  A lot of work.  Guess I'll be busy tomorrow.

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

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