File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.129: download - view: text, annotated - select for diffs
Sun Jan 29 19:39:03 2006 UTC (18 years, 5 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Fix bug 4490; parts correct works when weight for the problem = 0;

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

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